import mock from '@/utils/mockData'
import { getCurrentUser } from '@/services/userService'

// 从localStorage获取数据，如果没有则使用mock数据
function getPosts() {
  const posts = localStorage.getItem('blog_posts')
  return posts ? JSON.parse(posts) : mock.posts
}

function savePosts(posts) {
  localStorage.setItem('blog_posts', JSON.stringify(posts))
}

function getCommentsFromStorage() {
  const comments = localStorage.getItem('blog_comments')
  return comments ? JSON.parse(comments) : mock.commentsByPostId
}

function saveComments(comments) {
  localStorage.setItem('blog_comments', JSON.stringify(comments))
}

const rawCategories = mock.categories
const userMock = mock.userMock

function simulateDelay(result, delay = 200) {
  return new Promise((resolve) => setTimeout(() => resolve(result), delay))
}

function toSlug(title, id) {
  const base = String(title || '').toLowerCase().trim()
  const slug = base
    .replace(/[^a-z0-9\u4e00-\u9fa5\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
  return slug || `post-${id}`
}

function withDerivedFields(post) {
  return {
    ...post,
    slug: toSlug(post.title, post.id),
    // 兼容旧页面：用分类生成一个 tags 数组
    tags: Array.isArray(post.tags) ? post.tags : [post.category].filter(Boolean),
    // 兼容旧模板字段名：将 publishedAt 暴露为 date
    date: post.publishedAt,
  }
}

export async function fetchPosts({ page = 1, pageSize = 10, keyword = '', category = '' } = {}) {
  const kw = keyword.trim().toLowerCase()
  let filtered = getPosts()
  if (kw) {
    filtered = filtered.filter(p =>
      p.title.toLowerCase().includes(kw) ||
      p.summary.toLowerCase().includes(kw) ||
      String(p.content).toLowerCase().includes(kw)
    )
  }
  if (category) {
    filtered = filtered.filter(p => p.category === category)
  }
  const total = filtered.length
  const start = (page - 1) * pageSize
  const list = filtered.slice(start, start + pageSize).map(withDerivedFields)
  return simulateDelay({ list, total })
}

export async function fetchPostBySlug(slug) {
  const posts = getPosts()
  const post = posts.find(p => toSlug(p.title, p.id) === slug)
  return simulateDelay(post ? withDerivedFields(post) : null)
}

export async function fetchPostById(id) {
  const posts = getPosts()
  const post = posts.find(p => p.id === Number(id))
  return simulateDelay(post ? withDerivedFields(post) : null)
}

export async function fetchAllTags() {
  // 使用分类名作为"标签"集合；若未来有真实 tags 字段，可直接替换
  const set = new Set()
  getPosts().forEach(p => set.add(p.category))
  return simulateDelay(Array.from(set))
}

export async function fetchCategories() {
  // 直接返回 mock 中的分类统计
  return simulateDelay(rawCategories)
}

export async function savePost(post) {
  const currentUser = getCurrentUser()
  if (!currentUser) {
    throw new Error('请先登录')
  }
  
  const posts = getPosts()
  // 内存级保存：若存在则更新，不存在则新增
  const idx = posts.findIndex(p => p.id === post.id)
  if (idx >= 0) {
    // 检查是否为文章作者
    if (posts[idx].authorId !== currentUser.id) {
      throw new Error('只能编辑自己的文章')
    }
    posts[idx] = { ...posts[idx], ...post }
  } else {
    const nextId = posts.length > 0 ? Math.max(...posts.map(p => p.id)) + 1 : 1
    posts.push({ 
      ...post, 
      id: nextId, 
      authorId: currentUser.id,
      publishedAt: post.publishedAt || new Date().toISOString().split('T')[0],
      views: 0
    })
  }
  savePosts(posts)
  return simulateDelay(true, 300)
}

export async function getComments(postId) {
  const comments = getCommentsFromStorage()
  const list = comments[postId] || []
  return simulateDelay([...list])
}

export async function addComment(postId, content, author) {
  const currentUser = getCurrentUser()
  if (!currentUser) {
    throw new Error('请先登录才能发表评论')
  }
  
  const now = new Date()
  const pad = (n) => String(n).padStart(2, '0')
  const ts = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`
  const newItem = { 
    author: currentUser.username, 
    avatar: currentUser.avatar, 
    content, 
    createdAt: ts,
    userId: currentUser.id
  }
  
  const comments = getCommentsFromStorage()
  if (!comments[postId]) comments[postId] = []
  comments[postId].push(newItem)
  saveComments(comments)
  return simulateDelay(newItem, 200)
}

export async function deletePostById(id) {
  const currentUser = getCurrentUser()
  if (!currentUser) {
    throw new Error('请先登录')
  }
  
  const posts = getPosts()
  const idx = posts.findIndex(p => p.id === Number(id))
  if (idx >= 0) {
    // 检查是否为文章作者
    if (posts[idx].authorId !== currentUser.id) {
      throw new Error('只能删除自己的文章')
    }
    posts.splice(idx, 1)
    savePosts(posts)
    
    // 删除相关评论
    const comments = getCommentsFromStorage()
    delete comments[id]
    saveComments(comments)
    return simulateDelay(true, 200)
  }
  return simulateDelay(false, 100)
}


